package com.cherry.androidcode.recyclerView

import android.util.SparseIntArray
import androidx.annotation.CallSuper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.shuyu.gsyvideoplayer.utils.CommonUtil.dip2px

/**
 * @author DongMS
 * @since 2019/9/4
 */
abstract class AbsPinnedDataProvider<T, VH : QuickViewHolder>(private val layoutManager: RecyclerView.LayoutManager) : BaseItemProvider<T>() {

    private var mStaggeredGridItemHeights: SparseIntArray? = null

    override val itemViewType: Int = AbsPinnedHeaderListAdapter.TYPE_DATA

    @CallSuper
    override fun convert(h: BaseViewHolder, item: T) {
        val helper: VH = h as VH
        var position: Int = helper.adapterPosition
        if (position == RecyclerView.NO_POSITION) {
            return
        }
        position -= getAdapter()?.headerLayoutCount ?: 0

        if (layoutManager is StaggeredGridLayoutManager) {

            // 瀑布流布局记录高度，就不会导致Item由于高度变化乱跑，导致画分隔线出现问题
            if (mStaggeredGridItemHeights == null) {
                mStaggeredGridItemHeights = SparseIntArray()
            }

            if (mStaggeredGridItemHeights!!.get(position) == 0) {
                mStaggeredGridItemHeights!!.put(position, staggeredGridItemHeight(helper, item, position))
            }

            val lp = helper.itemView.layoutParams
            lp.height = mStaggeredGridItemHeights!!.get(position)
            helper.itemView.layoutParams = lp
        }

        convert(helper, item, position)
    }

    // 随机高度, 模拟瀑布效果,项目根据实际设置瀑布流高度
    open fun staggeredGridItemHeight(helper: VH, data: T, position: Int) = dip2px(helper.itemView.context, (100 + Math.random() * 100).toInt().toFloat())

    abstract fun convert(helper: VH, data: T, position: Int)

}